import { Modal, message as Message } from 'ant-design-vue'
import { useAuthStore } from '@/store'
import { useRouterStore } from '@/store'

let isConfirming = false
export function resolveResError(code: number, message: string) {
  const { route } = useRouterStore()

  switch (code) {
    case 401:
      if (isConfirming) return
      isConfirming = true

      setTimeout(() => {
        if (route.name == 'Login') return
        Modal.confirm({
          title: '提示',
          type: 'info',
          content: '登录已过期，是否重新登录？',
          onOk() {
            useAuthStore().logout()
            Message.success('已退出登录').then(() => {})
            isConfirming = false
          },
          onCancel() {
            isConfirming = false
          },
        })
      }, 600)
      return false
    case 402: {
      if (isConfirming) return
      isConfirming = true
      if (route.name == 'Login') return

      Modal.confirm({
        title: '提示',
        type: 'info',
        content: '当前账号已经在别的地方登录！',
        cancelText: '重新登录',
        onOk() {
          useAuthStore().logout()
          Message.success('已退出登录').then(() => {})
          isConfirming = false
        },
        onCancel() {
          useAuthStore().logout()
          Message.success('已退出登录').then(() => {})
          isConfirming = false
        },
      })

      return false
    }
    case 403:
      message = '请求被拒绝'
      break
    case 404:
      message = '请求资源或接口不存在'
      break
    case 500:
      message = '服务器发生异常'
      break
    default:
      message = message ?? `【${code}】: 未知异常!`
      break
  }

  return message
}
